package games.platformer.behaviors;

import vooga.entities.Entity;
import vooga.behaviors.*;
import java.util.Collection;


/**
 * Gravity Behavior - simulates gravity
 * A list of objects for which gravity should be disabled is included in the constructor
 * right now we put ladders in this list, so that if you're on a ladder and not pressing any key,
 * you stay where you are.
 * 
 * created 12-10
 * @author Ben Shelton
 * @author Congyi Wu
 */
public class GravityBehavior extends AbstractBehavior
{

	private double myGravity;
	private boolean myGravityEnabled;
	private boolean myGravityEnabledLastTime;
	private Collection<Entity> myEntities;
	
    public GravityBehavior(Collection<Entity> entities, double gravity)
    {
    	myGravity = gravity;
    	myEntities = entities;
    	myGravityEnabledLastTime = true;
    }
    
    /**
     * if the player character is in the air, increase their downward velocity
     */
    public void step (Entity target)
    {
    	myGravityEnabled = true;
    	
    	for(Entity e: myEntities)
    	{
    		if(target.intersects(e))
    		{
    			myGravityEnabled = false;
    			break; // i realize this isn't elegant, but there's no way around it for this for loop structure
    		}
    	}
    	
    	if(myGravityEnabled) // if we're supposed to use gravity
    	{
    		target.getVelocity().setYChange(target.getVelocity().getYChange() + myGravity); // add gravity
    		myGravityEnabledLastTime = true; // set flag - gravity was enabled on last cycle
    	}
    	else // otherwise
    	{
    		if(myGravityEnabledLastTime == true) // if gravity was enabled last time but not this time
    		{
    			target.getVelocity().setYChange(0); // set y velocity to 0
    			myGravityEnabledLastTime = false; // set flag - gravity was not enabled on last cycle
    		}
    	}
    }
}
